package com.haizhi.gsxt;

import com.haizhi.enums.Province;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.WriteModel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bson.Document;

import java.util.ArrayList;
import java.util.List;

public class ProvinceStore {

    private static final Logger logger = LogManager.getLogger(ProvinceStore.class);

    //批量插入数目
    private static final Integer BATCH_INSERT_NUM = 500;

    private Province province;
    private MongoCollection<Document> collection;
    private List<WriteModel<Document>> requests = new ArrayList<>();

    public ProvinceStore(Province province, MongoDatabase mongoDatabase) {
        this.province = province;
        this.collection = mongoDatabase.getCollection(ProvinceTable.getProvinceTable(province.getValue()));
        logger.info("当前省份 {} 存储实例初始化完成...", province.getValue());
    }

    public void batchStoreDocument(WriteModel<Document> documentWriteModel) {
        if (null == documentWriteModel) {
            logger.error("没有传入有效参数");
            return;
        }

        requests.add(documentWriteModel);
        if (requests.size() > BATCH_INSERT_NUM) {
            collection.bulkWrite(requests);
            logger.info("定量插入结果: {} {}", province.getValue(), requests.size());
            requests.clear();
        }
    }

    //批量存储
    public void storeDocument(List<WriteModel<Document>> requests) {
        collection.bulkWrite(requests);
    }

    public void batchStoreTiming() {
        if (requests.size() > 0) {
            collection.bulkWrite(requests);
            logger.info("定时插入结果: {} {}", province.getValue(), requests.size());
            requests.clear();
        }
    }
}
